package com.ie.intelligence_education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.intelligence_education.mapper.TeacherMapper;
import com.ie.intelligence_education.pojo.Teacher;
import com.ie.intelligence_education.service.TeacherService;
import com.ie.intelligence_education.utils.Result;
import com.ie.intelligence_education.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
@Slf4j
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public Result login(Teacher teacher, HttpServletRequest request) {
        //将教师的密码转为密文
        String password = teacher.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        teacher.setPassword(md5Password);
        //条件构造器
        LambdaQueryWrapper<Teacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teacher::getUsername,teacher.getUsername());
        Teacher teacher1 = teacherMapper.selectOne(lambdaQueryWrapper);
        //如果用户不存在
        if (teacher1 == null) {
            log.info("用户不存在");
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        //如果用户存在，进行密码判断
        if (!teacher1.getPassword().equals(teacher.getPassword())){
            log.info("输入的密码错误");
            return Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
        }
        //来到此处，说明密码正确
        //将用户的id存入session中，方便后期的登录验证
        request.getSession().setAttribute("teacher",teacher.getId());
        log.info("存入的session为" + request.getSession().getAttribute("teacher"));
        return Result.ok(null);
    }
}
